package org.example.service.impl;

import org.example.dao.AccountDao;
import org.example.entity.Account;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        // 用于配置类创建对象
        this.accountDao = accountDao;
    }

    @Override
    @Transactional// 事务注解,这个注解不需要进行包扫描,直接找配置文件
    public void transfer(String from, String to, float amount) {
        Account fromAccount = accountDao.findAccount(from);// 转账账户
        Account toAccount = accountDao.findAccount(to);// 接收账户

        if (fromAccount != null && toAccount != null) {
            fromAccount.setMoney(fromAccount.getMoney() - amount);
            toAccount.setMoney(toAccount.getMoney() + amount);

            System.out.println(accountDao.updateAccount(fromAccount));
            System.out.println(10/0);// 模拟异常
            System.out.println(accountDao.updateAccount(toAccount));
        }
    }
}
